<?php

namespace app\api\model;

use app\common\model\Order;
use think\Db;
use think\Exception;
use think\Model;
use think\model\Merge;

class ShopComment extends Merge
{
    protected $autoWriteTimestamp = true;
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $visible = ['id','nickname','avatar','content','score','createtime'];

    public function user()
    {
        return $this->belongsTo('User','user_id','id','LEFT')->bind('nickname,avatar');
    }

    protected function base($query)
    {
        $mpId = get_api_applet_id();
        $globalKey = [
            'mp_id'=>$mpId,
        ];
        $query->where($globalKey);
    }

    //根据商品Id 获取评论
    public static function getList($proId, $page = 1, $row = 5)
    {
        $map = [
//            'pro_id' => 1,
        ];
        $res['data'] = self::where($map)
            ->with('user')
            ->page($page, $row)
            ->order('createtime desc')
            ->select();
        $res['total'] = $total = self::where($map)->count();
        $res['has_more'] = ceil($total / $row) > $page ? true : false;
        return $res;
    }

    public function saveComments($orderNo, $userId, $comments)
    {
        try{
            Db::startTrans();
            $order = ShopOrder::where('order_no', $orderNo)
                ->where('user_id', $userId)
                ->where('status', Order::ORDER_WAIT_COMMENT)
                ->find();
            if (!$order)
                return ['_code' => 404, 'msg' => '该订单 不存在/不可评价'];

            foreach ($comments as $k => &$comment) {
                $map = [
                    'pro_id'=>$comment['pro_id'],
                    'order_id'=>$order['id'],
                ];
                //判断是否存在该商品
                if(ShopOrderItem::get($map)){
                    $comment['mp_id'] = get_api_applet_id();
                    $comment['user_id'] = $userId;
                }else{
                    unset($comments[$k]);
                }
            }
            $res = self::saveAll($comments);
            if (count($res) > 0){
                $order->status = Order::ORDER_COMPLETE;
                $order->save();
                Db::commit();
                return ['_code' => 201, 'msg' => '评论成功'];
            }else{
                return ['_code' => 500, 'msg' => '评论失败'];
            }
        }catch(Exception $e){
            Db::rollback();
            throw $e;
        }
    }

    public function getCreatetimeAttr($value)
    {
        return date('Y-m-d H:i',$value);
    }

    public function getUpdatetimeAttr($value)
    {
        return date('Y-m-d H:i',$value);
    }
}
